﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.ModelBinding;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;
using Backend.Api.Models;
using Backend.Api.Providers;
using Backend.Api.Results;
using Backend.Data.Managers;
using Backend.Data.Entities;

using System.Linq;
using System.Web.Http.Cors;

namespace Backend.Api.Controllers
{

    //[Authorize]
    //[RoutePrefix("api/Account")]
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class RoleController : ApiController
    {
        private ApplicationRoleManager _roleManager;

        public ApplicationRoleManager RoleManager
        {
            get
            {
                return _roleManager ?? HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
            }
            private set
            {
                _roleManager = value;
            }
        }


        //[AllowAnonymous]
        //[AllowAnonymous]
        //[AllowAnonymous]
        //[Authorize(Roles = "User")]
        // GET api/<controller> //[Route("GetAllApplicationRoles")]
        public IEnumerable<RoleModel> GetAllApplicationRoles()
        {
            var userAuthInfo = HttpContext.Current.User;
            string userId=userAuthInfo.Identity.GetUserId();

            return RoleManager.Roles.Select(t => new RoleModel
            {
                Id = t.Id,
                Name = t.Name,
                Description = userId,
            });
        }

        // GET api/<controller>/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/<controller>
        public async Task<IHttpActionResult> Post([FromBody]RoleModel m)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            IdentityResult r = await RoleManager.CreateAsync(new ApplicationRole
            {
                Name = m.Name,
                Description = m.Description,
            });
            if (!r.Succeeded)
            {
                //ModelState.AddModelError("", r.Errors.First());
                return GetErrorResult(r);
            }

            return Ok();
        }

        // PUT api/<controller>/5
        public async Task<IHttpActionResult> Put(Guid id, [FromBody]RoleModel m)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            ApplicationRole role = await RoleManager.FindByIdAsync(m.Id);
            role.Name = m.Name;
            role.Description = m.Description;
            IdentityResult r = await RoleManager.UpdateAsync(role);
            if (!r.Succeeded)
            {
                //ModelState.AddModelError("", r.Errors.First());
                return GetErrorResult(r);
            }

            return Ok();
        }

        // DELETE api/<controller>/5
        public async Task<IHttpActionResult> Delete(string id)
        {

            ApplicationRole role = await RoleManager.FindByIdAsync(id);

            IdentityResult r = await RoleManager.DeleteAsync(role);
            if (!r.Succeeded)
            {
                //ModelState.AddModelError("", r.Errors.First());
                return GetErrorResult(r);
            }

            return Ok();
        }

        protected override void Dispose(bool disposing)
        {
            /*if (disposing && _userManager != null)
            {
                _userManager.Dispose();
                _userManager = null;
            }*/

            if (disposing)
            {
                //UserManager.Dispose();
                RoleManager.Dispose();
            }

            base.Dispose(disposing);
        }

        #region
        private IHttpActionResult GetErrorResult(IdentityResult result)
        {
            if (result == null)
            {
                return InternalServerError();
            }

            if (!result.Succeeded)
            {
                if (result.Errors != null)
                {
                    foreach (string error in result.Errors)
                    {
                        ModelState.AddModelError("", error);
                    }
                }

                if (ModelState.IsValid)
                {
                    // No hay disponibles errores ModelState para enviar, por lo que simplemente devuelva un BadRequest vacío.
                    return BadRequest();
                }

                return BadRequest(ModelState);
            }

            return null;
        }
        #endregion
    }
}